<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyrandom" size="small" placeholder="Key" style="width: 200px; " class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.tablename" size="small" placeholder="表名 [模糊查询]" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.tablenameshow" size="small" placeholder="表名/菜单名[模糊查询]" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.deleteflag" size="small" placeholder="状态" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 0px;" size="small" type="primary" icon="el-icon-edit" @click="handleCreateBuildCode">
        源码生成器
      </el-button>
      <el-button class="filter-item" style="margin-left: 0px;" size="small" icon="el-icon-setting" @click="pageSettingVisible=true">
        页面设置
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        v-for="(col, index) in formThead"
        :key="index"
        :prop="col.name"
        :sortable="col.sort"
        :sort-orders="['ascending', 'descending']"
        :label="col.title"
        :width="col.width"
      >
        <template slot-scope="{row}">
          <span v-if="col.edit">
            <el-input v-if="row.edit" v-model="row[col.name]" class="edit-input" size="mini" />
            <span v-else>{{ row[col.name] }}</span>
          </span>
          <span v-else>{{ row[col.name] }}</span>
        </template>
      </el-table-column>

      <!--操作Button-->
      <el-table-column v-if="!isDropMenu" fixed="right" align="center" min-width="360">
        <template slot="header">
          <el-checkbox v-model="isDropMenu" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
            平铺->下拉
          </el-checkbox>
        </template>
        <template slot-scope="{row}">
          <el-button v-show="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="cancelEdit(row)">取消</el-button>
          <el-button v-if="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="confirmEdit(row)">保存</el-button>
          <el-button v-else type="primary" size="mini" style="margin-left: 0px;" @click="row.edit=!row.edit">编辑</el-button>
          <el-button slot="reference" type="primary" size="mini" style="margin-left: 0px;" @click="handleCreateBuildCode4Row(row)">生成源码</el-button>
          <el-button type="primary" size="mini" style="margin-left: 0px;" @click="handleShowColumnList(row)">列管理</el-button>
          <el-button slot="reference" size="mini" type="danger" style="margin-left: 0px;" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>

      <el-table-column v-else fixed="right" label="操作" align="center" min-width="140">
        <template slot="header">
          <el-checkbox v-model="isDropMenu" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
            下拉->平铺
          </el-checkbox>
        </template>
        <template slot-scope="{row,$index}">
          <el-button v-show="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="cancelEdit(row)">取消</el-button>
          <el-button v-if="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="confirmEdit(row)">保存</el-button>
          <el-dropdown v-else @command="handleCommand">
            <el-button type="primary" size="mini">
              菜单<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'coding')">生成源码</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'column')">列管理</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'update')">编辑</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'delete')">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!--源码生成器-->
    <el-dialog title="源码生成器" :visible.sync="dialogForm4CodeVisible">
      <build-code />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm4CodeVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialog4ColumnListVisible" title="列管理" width="90%">
      <TmptColumnList :a1templatetable-id="a1templatetableId" />
    </el-dialog>

    <el-dialog :visible.sync="preview.visible" title="预览" width="90%">
      <tmpt-preview :key-random-prop="preview.keyRandom" :preview-visible="preview.visible" />
    </el-dialog>

    <el-dialog :visible.sync="pageSettingVisible" title="页面设置">
      <div>
        <h3>列表显示列：</h3>
        <el-checkbox-group v-model="checkboxVal">
          <el-checkbox v-for="(thead,index) in theadOptions" :key="index" :label="thead.name" style="width: 150px;">{{ thead.title }}</el-checkbox>
        </el-checkbox-group>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savePageSetting">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, updateApi, removeApi, addTemplatetableColumnApi, gen2LevelMenuApi } from './tmpt-list-api'
import waves from '@/directive/waves' // waves directive
import { parseTime, deleteEmptyProperty } from '@/utils'
import storageUtil from '@/utils/StorageUtil'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import BuildCode from './build-code'
import TmptColumnList from './tmpt-column-list'
import TmptPreview from './tmpt-preview'

const ColumnShowListCkedKey = 'tmpt-list-column-show-cked-list-key'
const isDropMenuKey = 'tmpt-list-column-show-isdropmenu-key'

// 所有列对象
const theadOptions = [
  { name: 'id', title: 'ID', width: 80, edit: false, sort: 'custom', default: true },
  { name: 'keyrandom', title: 'Key', width: 200, edit: false, sort: false, default: true },
  { name: 'tablename', title: '表名', width: 200, edit: true, sort: false, default: true },
  { name: 'tablenameshow', title: '表名描述', width: 200, edit: true, sort: false, default: true },
  { name: 'tablealiasname', title: '表别名', width: 200, edit: true, sort: false, default: true },
  { name: 'foreignkey', title: '外键', width: 200, edit: true, sort: false, default: true },
  { name: 'hasaddbtn', title: '添加BTN', width: 80, edit: true, sort: false, default: true },
  { name: 'hasdownloadreportbtn', title: '下载BTN', width: 80, edit: true, sort: false, default: true },
  { name: 'haseditbtn', title: '编辑BTN', width: 80, edit: true, sort: false, default: true },
  { name: 'hasdelbtn', title: '删除BTN', width: 80, edit: true, sort: false, default: true },
  { name: 'hascheckbox', title: '行多选框', width: 80, edit: true, sort: false, default: true },
  { name: 'tablenamesql', title: '表sql', width: 300, edit: true, sort: false, default: true },
  { name: 'deleteflag_Str', title: '状态', width: 80, edit: true, sort: false, default: true },
  { name: 'createdate', title: '创建日期', width: 200, edit: false, sort: false, default: true },
  { name: 'createman', title: '创建人', width: 200, edit: false, sort: false, default: true }
]

export default {
  name: 'TmptList',
  components: { BuildCode, Pagination, TmptColumnList, TmptPreview },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },

  data() {
    return {
      tableKey: 0,
      // 控制行尾菜单显示模式（下拉->平铺）
      isDropMenu: storageUtil.readBool(isDropMenuKey),
      // 默认表头控制
      theadOptions: theadOptions,
      checkboxVal: [], // checkboxVal
      formThead: [], // 默认表头 Default header

      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: '-id',
        deleteflag: 0
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {},
      dialogFormVisible: false,
      dialogForm4CodeVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      downloadLoading: false,
      dialog4ColumnListVisible: false,
      a1templatetableId: 0,
      preview_menu_id: 667,
      coding_menu_id: 668,
      preview: {
        keyRandom: 0,
        visible: false
      },
      pageSettingVisible: false
    }
  },

  watch: {
    checkboxVal(valArr) {
      this.formThead = this.theadOptions.filter(i => valArr.indexOf(i.name) >= 0)
      this.tableKey = this.tableKey + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
    },
    isDropMenu(val) {
      storageUtil.saveBool(isDropMenuKey, val)
    }
  },

  created() {
    this.initLayout()
    this.getList()
  },

  methods: {
    initLayout() {
      const defaultCheckedThead = []
      theadOptions.forEach(col => {
        if (col.default) {
          defaultCheckedThead.push(col.name)
        }
      })
      // read localstorage first
      const columnShowListCked = storageUtil.readArr(ColumnShowListCkedKey)
      if (columnShowListCked.length === 0) {
        this.checkboxVal = defaultCheckedThead
      } else {
        this.checkboxVal = columnShowListCked
      }
    },

    getList() {
      this.listLoading = true
      deleteEmptyProperty(this.listQuery)
      fetchList(this.listQuery).then(result => {
        const items = result.map.rows
        this.total = result.map.total

        // 备份数据，编辑还原用
        this.list = items.map(v => {
          this.$set(v, 'edit', false)
          v.original = Object.assign({}, v)
          return v
        })

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.1 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },
    savePageSetting() {
      storageUtil.saveArr(ColumnShowListCkedKey, this.checkboxVal)
      this.pageSettingVisible = false
    },
    // 下拉操作菜单
    beforeHandleCommand(index, row, command) {
      return {
        'index': index,
        'row': row,
        'command': command
      }
    },
    handleCommand(command) {
      const row = command.row
      switch (command.command) {
        case 'coding': {
          this.handleCreateBuildCode4Row(row)
          break
        }
        case 'column': {
          this.handleShowColumnList(row)
          break
        }
        case 'update': {
          row.edit = !row.edit
          break
        }
        case 'delete': {
          this.handleDelete(row)
          break
        }
      }
    },
    // End

    // 源码生成器，在子组件中生成
    handleCreateBuildCode() {
      this.dialogForm4CodeVisible = true
    },
    // 行尾，重新生成源码
    handleCreateBuildCode4Row(row) {
      this.$confirm('重新生成的源码，将覆盖原有源码，请备份好，再执行？')
        .then(() => {
          this.addTemplatetableColumn(row)
        })
        .catch(_ => {})
    },

    // add template table column
    addTemplatetableColumn(row) {
      var data = {}
      data._id = row.id
      addTemplatetableColumnApi(data).then(result => {
        // this.showInLogs("增加'模板表列'结果：" + result.content, data1.tableName, result.code)
        this.$notify({
          title: '结果',
          message: "'模板列'自动扫库结果：" + result.content,
          type: 'success',
          duration: 5000
        })

        // generator 2 level menu 预览模式
        // 627 is 预览菜单的 menuId
        // gen2LevelMenu('datagrid', '预览模式', data1.tableName + '_', preview_menu_id, a1TemplateTableId, data1)
        this.gen2LevelMenu('datagrid-sourcecode', '源码模式', row)

        // generator 2 level menu 源码模式
        // 628 is 源码菜单的 menuId
        // if (mode == 'code') {
        // gen2LevelMenu('datagrid-sourcecode', '源码模式', data1.tableName, coding_menu_id, a1TemplateTableId, data1)
        // }
      })
    },
    // generator 2 level menu
    gen2LevelMenu(pageType, modeStr, row) {
      const data = {
        'menu1Id': this.coding_menu_id,
        '_id': row.id,
        'pageType': pageType,
        'menu2Name': row.tablename,
        'keyRandom': row.keyrandom
      }
      gen2LevelMenuApi(data).then(result => {
        // this.showInLogs("创建二级菜单'" + modeStr + "'结果：" + result.content, data1.tableName, result.code)
        // this.showInLogs('源码生成结果：' + result.content, data1.tableName, result.code)
        this.$notify({
          title: '结果',
          message: '源码生成结果：' + result.content,
          type: 'success',
          duration: 5000
        })
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除吗？')
        .then(_ => {
          removeApi({ id: '' + row.id }).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(_ => {})
    },

    handleShowColumnList(row) {
      this.a1templatetableId = Number(row.id)
      this.dialog4ColumnListVisible = true
    },

    cancelEdit(row) {
      // 还原原始值
      Object.keys(row).forEach(key => {
        if (key !== 'original' && key !== 'edit') {
          row[key] = row.original[key]
        }
      })
      row.edit = false
      // row.original.edit = false
      this.$message({
        message: '数据恢复到原始值',
        type: 'warning'
      })
    },
    confirmEdit(row) {
      const param = Object.assign({}, row)
      param.original = {}
      updateApi(param).then((result) => {
        if (result.success) {
          row.edit = false
          // 原始值：更新成最新输入仠
          Object.keys(row).forEach(key => {
            if (key !== 'original' && key !== 'edit') {
              row.original[key] = row[key]
            }
          })
          this.$notify({
            title: '成功',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
</style>
